package com.googlecode.bizyap.core;

import java.util.Set;
import java.util.regex.Pattern;

public class Application {

	private String contextPath;
	private boolean ssoApplication;
	private boolean valid = true;

	private Pattern logoutPattern = null;
	private Pattern[] securePatterns = null;

	private String authClassName = null;

	public Application(String contextPath) {
		super();
		this.contextPath = contextPath;
		this.ssoApplication = false;
	}

	public Application(String contextPath, boolean valid) {
		this(contextPath);
		this.valid = valid;
	}

	/**
	 * @throws Exception (Pattern compile may throw an unchecked exception...)
	 */
	public Application(String contextPath, String logoutPath, Set<String> patterns) throws Exception {
		super();
		this.contextPath = contextPath;
		this.logoutPattern = Pattern.compile(logoutPath);

		if(patterns!=null){
			int size = patterns.size();
			securePatterns = new Pattern[size];
			int i = 0;
			for (String pattern : patterns) {
				securePatterns[i++] = Pattern.compile(pattern);
			}
		}

		if(securePatterns==null || securePatterns.length==0){
			this.ssoApplication = false;
		}
		else {
			this.ssoApplication = true;
		}
	}

	public Application(String contextPath, String logoutPath, Set<String> patterns, String authClassName) throws Exception {
		this(contextPath, logoutPath, patterns);
		this.authClassName = authClassName;
	}

	public String getContextPath() {
		return contextPath;
	}

	public boolean isLoggingOut(String url){
		return logoutPattern!=null && logoutPattern.matcher(url).find();
	}

	public boolean requiresSecurityCheck(String url){
		if(ssoApplication){
			if(securePatterns!=null){
				for (Pattern pattern : securePatterns) {
					if(pattern.matcher(url).find()){
						return true;
					}
				}
			}
		}
		return false;
	}

	public boolean isSSOApplication(){
		return ssoApplication;
	}

	public boolean isValid(){
		return valid;
	}

	public String getAuthorizationClassName(){
		return authClassName;
	}

	@Override
	public int hashCode() {
		return contextPath==null ? 0 : contextPath.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;

		if(this.contextPath == null)
			return false;

		final Application other = (Application) obj;
		if(this.contextPath.equals(other.contextPath)){
			return true;
		}
		return false;
	}

	@Override
	public String toString() {
		return "Application[ ctx: " + contextPath + ", sso: " + ssoApplication + " ]";
	}
}
